package com.jetlion.filestorage;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private final String FILE_NAME = "demo";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {

        Button writeBtn = findViewById(R.id.write_btn);

        Button readBtn = findViewById(R.id.read_btn);

        TextView textView = findViewById(R.id.text);

        writeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int i = new Random().nextInt(1000);
                write(i);
            }
        });

        readBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int i = read();
                textView.setText("the num is:" + i);
            }
        });
    }


    /**
     * 通过io流写进文件
     *
     * @param i
     */
    private void write(int i) {

        Log.i("TAG", "write: " + i);
        FileOutputStream outputStream = null;
        try {
            outputStream = openFileOutput(FILE_NAME, MODE_PRIVATE);
            outputStream.write(String.valueOf(i).getBytes());
            //关闭输出流
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过id流读取文件内容
     *
     * @return
     */
    private Integer read() {
        try {
            FileInputStream inputStream = openFileInput(FILE_NAME);

            byte[] buffer = new byte[50];
            int len;
            //
            StringBuffer stringBuffer = new StringBuffer();

            while ((len = inputStream.read(buffer)) != -1) {
                String str = new String(buffer, 0, len);
                //拼接字符串
                stringBuffer.append(str);
            }
            //关闭输入流
            inputStream.close();

            //转换成字符串
            String value = stringBuffer.toString();

            int i = Integer.parseInt(value);
            return i;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}